package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {

    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 0/5 * * * ?")
    // @Scheduled(cron = "1/5 * * * * ?")
    public void timeoutOrder() {
        log.info("{}: 清理超时订单", LocalDateTime.now());

        // 查找超时订单
        List<Long> ids = orderMapper.getIdsByTime(LocalDateTime.now().plusMinutes(-15), Orders.PENDING_PAYMENT);

        // 设置 status 为超时（6）
        if (ids != null && !ids.isEmpty()) {
            for(Long id: ids) {
                Orders orders = Orders.builder()
                        .id(id)
                        .status(Orders.CANCELLED)
                        .cancelTime(LocalDateTime.now())
                        .cancelReason("订单超时")
                        .build();
                orderMapper.update(orders);
            }
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "1/5 * * * * ?")
    public void deliveryOrder() {
        log.info("{}: 处理派送中的订单", LocalDateTime.now());

        // 查询昨天还在配送的订单
        List<Long> ids = orderMapper.getIdsByTime(LocalDateTime.now().plusMinutes(-60), Orders.DELIVERY_IN_PROGRESS);

        // 设置 status 为完成（5）
        if (ids != null && !ids.isEmpty()) {
            for(Long id: ids) {
                Orders orders = Orders.builder()
                        .id(id)
                        .status(Orders.COMPLETED)
                        .build();
                orderMapper.update(orders);
            }
        }
    }

}
